from machine import I2C, Pin
from ssd1306 import SSD1306_I2C
import time
def getI2Cstatue():
    # 初始化 I2C 接口
    i2c = I2C(0, scl=Pin(22), sda=Pin(21))  # 根据实际接线调整 Pin 脚
    devices = i2c.scan()
    # oled = SSD1306_I2C(128, 64, i2c)
    if devices:
#         print("I2C devices found:", [hex(d) for d in devices])
        # 初始化 OLED 显示屏
        oled = SSD1306_I2C(128, 64, i2c)  # 宽 128px，高 64px，I2C 地址默认为 0x3C
        # 清屏并显示文字
#         oled.fill(0)  # 清空屏幕
#         oled.text("OLED Test", 0, 20)
#         oled.show()  # 刷新屏幕
        return oled
    else:
        print("No I2C devices found")
        return False
    



# 定义 OLED 打印类
class OLEDPrinter:
    def __init__(self, oled, line_height=10, max_lines=6, screen_width=128):
        self.oled = oled
        self.line_height = line_height  # 每行文字高度
        self.max_lines = max_lines      # 最多显示的行数
        self.lines = []                 # 存储显示的行
        self.screen_width = screen_width
        self.char_width = 8  # 每个字符约占宽度 (适用于默认字体)

    def split_text(self, text):
        """将文字按屏幕宽度拆分为多行"""
        max_chars = self.screen_width // self.char_width  # 每行最多字符数
        wrapped_lines = []
        while len(text) > max_chars:
            wrapped_lines.append(text[:max_chars])  # 截取一行
            text = text[max_chars:]  # 剩余部分继续处理
        wrapped_lines.append(text)  # 添加最后一行
        return wrapped_lines

    def print(self, *args, sep=' ', end='\n'):
        # 将打印内容转为字符串
        text = sep.join(map(str, args)) + end
        for line in text.splitlines():
            # 拆分超长行
            wrapped_lines = self.split_text(line)
            for wrapped_line in wrapped_lines:
                self.lines.append(wrapped_line)
                if len(self.lines) > self.max_lines:  # 超过最大行数，移除顶部一行
                    self.lines.pop(0)
        
        # 清屏并显示内容
        self.oled.fill(0)  # 清屏
        for i, line in enumerate(self.lines):
            self.oled.text(line, 0, i * self.line_height)  # 显示每一行
        self.oled.show()

import _thread

# 定义线程中执行的打印任务
def threaded_print(oled_printer,*args, **kwargs):
    def task():
        oled_printer.print(*args, **kwargs)
    # 使用 _thread 启动新线程
    _thread.start_new_thread(task, ())

if __name__=="__main__":
    w=getI2Cstatue()
    if w:
        oled_printer = OLEDPrinter(w)  
        global print  # 声明 print 为全局变量
        def print(*args, **kwargs):
            threaded_print(oled_printer,*args, **kwargs)
# 长文字测试
    print("This is a very long line that should automatically wrap to the next line.")
    time.sleep(1)
    print("MicroPython OLED!")
    i=1
    while True:
        print (f"{i} test",end=" ")
        time.sleep_ms(300)
        i+=1
